//@flow

import {
    FetchDataRequest,
    FetchDataSuccess,
    FetchDataFailed,
    FetchDataCancle,
} from './RefreshActionTypes'

import {Map} from 'immutable'

import RefreshData from './RefreshInitState'

const initState = Map()

export default function (state = initState, action) {
    switch (action.type) {
        case FetchDataRequest:
            return update(state, action)
                .setIn([action.identifier, 'isRefreshing'], true)
                .removeIn([action.identifier, 'isCancle'])
                .removeIn([action.identifier, 'error'])
                .removeIn([action.identifier, 'data'])
        case FetchDataSuccess:
            return update(state, action)
                .setIn([action.identifier, 'isRefreshing'], false)
                .setIn([action.identifier, 'data'], action.model)
                .removeIn([action.identifier, 'isCancle'])
                .removeIn([action.identifier, 'error'])
        case FetchDataFailed:
            return update(state, action)
                .setIn([action.identifier, 'isRefreshing'], false)
                .setIn([action.identifier, 'error'], action.error)
        case FetchDataCancle:
            return update(state, action)
                .delete(action.identifier)
        default:
            return state
    }
}

function update(state, action) {
    let newState = state
    const identifier = action.identifier
    if (!state.get(identifier)) {
        newState = state.set(identifier, new RefreshData())
    }
    return newState
}